package com.shen;

import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

/**
 * 事务测试
 */
public class TestTX {
    public static void main(String[] args) {
        //建立一个连接
        Jedis jedis = new Jedis("192.168.174.131");
        jedis.auth("123456");

        //清空数据库
        jedis.flushDB();

        //准备数据
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("hello","world");
        jsonObject.put("name","shen");
        String s = jsonObject.toJSONString();

        //开启事务
        Transaction multi = jedis.multi();

        try{

            multi.set("user1",s);
            multi.set("user2",s);
            int i =1/0;//代码出现异常，事务会执行放弃事务
            //执行事务
            multi.exec();
        }catch (Exception e){
            //放弃事务
            multi.discard();
            e.printStackTrace();
        }finally {
            System.out.println(jedis.get("user1"));
            System.out.println(jedis.get("user2"));
            //关闭连接
            jedis.close();
        }

        /**
         * {"name":"shen","hello":"world"}
         * {"name":"shen","hello":"world"}
         */

    }
}
